package com.apps.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.apps.common.model.po.ApiResult;
import com.apps.config.AliPayConfig;
import com.apps.helper.PageConextHelper;
import com.apps.helper.UserConextHelper;
import com.apps.order.enums.PayType;
import com.apps.order.model.po.KupaVipGoodsOrder;
import com.apps.order.service.IKupaOrder;
import com.apps.order.service.IKupaVipGoodsOrderService;
import com.apps.thirdparty.pay.alipay.model.po.KupaAlipayCallback;
import com.apps.thirdparty.pay.alipay.service.IKupaAlipayService;
import com.apps.thirdparty.pay.alipay.utils.IKupaAlipayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 付款控制器
 */
@Slf4j
@Controller
@RequestMapping(value = "/alipay")
public class AliPayController
{

    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private IKupaAlipayService alipayService;

    @Autowired
    private IKupaVipGoodsOrderService vipGoodsOrderService;

    @Autowired
    List<IKupaOrder> kupaOrders;

    /**
     * 支付宝支付
     * @param vip_goods_id
     * @param request
     * @param httpResponse
     */
    @RequestMapping("/pay.html")
    public void Pay(Integer vip_goods_id,
                    HttpServletRequest request,
                    HttpServletResponse httpResponse)
    {
        try
        {
            httpResponse.setContentType("text/html;charset=UTF-8");
            KupaVipGoodsOrder vipGoodsOrder=vipGoodsOrderService.CreateOrder(UserConextHelper.getCurrentMember().getId(),vip_goods_id);
            //直接将完整的表单html输出到页面
            httpResponse.getWriter().write(alipayService.Alipay(vipGoodsOrder.getSn(),vipGoodsOrder.getVip_goods_name(),vipGoodsOrder.getPay_price()));
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝同步回调
     * @param request
     * @param httpResponse
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/AlipayCallback")
    public void PayCallback(HttpServletRequest request,
                            HttpServletResponse httpResponse)  throws Exception
    {
        ApiResult<String> result = new ApiResult<>();
        Map<String, String> paramsMap = IKupaAlipayUtils.convertRequestParamsToMap(request); //将异步通知中收到的所有参数都存放到map中
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, aliPayConfig.getAliPubkey() , "UTF-8",aliPayConfig.getPc_signType()); //调用SDK验证签名
        if(signVerified)
        {
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //参数解析成模型
            KupaAlipayCallback alipayCallback=new KupaAlipayCallback(paramsMap);
            //处理
            for(IKupaOrder order:kupaOrders)
                order.PaySuccess(alipayCallback.getTrade_no(),alipayCallback.getOut_trade_no(),alipayCallback.getTotal_amount(), PayType.ALIPAY);
            //回到历史页面
            httpResponse.sendRedirect(PageConextHelper.getHistoryPage());
        }else
        {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            log.info("验签失败");
        }
    }
}
